package com.example.lxq.demo;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.example.lxq.demo.config.MyMouseListener;
import com.example.lxq.demo.config.SpringListener;
import com.example.lxq.demo.config.SpringObserver;

public class Launcher extends JFrame implements SpringListener {
    /**
     *
     */
    private boolean loading = false;
    private DemoApplication app;
    private static final long serialVersionUID = 1L;
    private StringBuffer stringBuffer;
    private JTextArea textArea;
    private JButton showIp;
    private JButton startBtn;
    private Font font;
    private JLabel pathView;
    private String pathString="";

    public static void main(String[] args) {
        new Launcher();
    }

    private void initComponent() {
        showIp = new JButton();
        showIp.setBounds(10, 400, 460, 50);
        showIp.setVisible(false);
        add(showIp);
        openBrowse();
        startBtn = new JButton("启动");
        startBtn.setFont(font);
        pathView = new JLabel();
        textArea = new JTextArea();
        pathView.setText("请选择路径");
        registerLisetener();
    }

    private void registerLisetener() {
        pathView.addMouseListener(new MyMouseListener(){

            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int code=chooser.showDialog(new JLabel(), "选择项目文件夹");
                if(code==JFileChooser.APPROVE_OPTION){
                    pathView.setText(chooser.getSelectedFile().getAbsolutePath());
                    pathString=chooser.getSelectedFile().getAbsolutePath();
                    SpringObserver.vPath=pathString;
                }
            }
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            public void mouseExited(MouseEvent e) { 
            }
            public void mouseDragged(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
            public void mouseMoved(MouseEvent e) {
                // TODO Auto-generated method stub
                
            }
        });
    }

    public Launcher() {
        setLayout(null);
        setSize(500, 500);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | UnsupportedLookAndFeelException e1) {
            e1.printStackTrace();
        }
        setLocationRelativeTo(getOwner());
        setResizable(false);
        setTitle("快捷预览");
        initComponent();
        stringBuffer = new StringBuffer();
        startBtn.setBounds(390, 10, 90, 50);
        add(startBtn, BorderLayout.CENTER);
        pathView.setBounds(10, 10, 380, 50);
        add(pathView, BorderLayout.NORTH);
        startBtn.addActionListener(e -> {
            SpringObserver.vPath="D:\\model space/";
            if (loading) {
                app = null;
                System.gc();
                loading = false;
                stringBuffer.append("\n" + getTime() + "web服务已停止");
                console(stringBuffer.toString());
                startBtn.setText("启动");
                SpringObserver.context.close();
                showIp.setText("web服务已停止");
                showIp.setVisible(false);
            } else {
                setTitle("正在启动");
                new Thread(() -> {
                    SpringObserver.springListener = Launcher.this;
                    app = new DemoApplication();
                    app.start(Launcher.this);
                }).run();
            }

        });
        textArea.setBounds(10, 70, 470, 200);
        textArea.setLineWrap(true);
        add(textArea);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void openBrowse() {
        showIp.addActionListener((event) -> {
            try {
                Runtime.getRuntime()
                        .exec("rundll32 url.dll,FileProtocolHandler " + "http://" + getHostAddress() + "/preview.html");
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        });
    }

    private String getHostAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress() + ":8080";
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "localhost:8080";
    }

    private void console(String str) {
        textArea.setText(str);
    }

    private String getTime() {
        return new SimpleDateFormat("HH:mm:ss").format(new Date()) + " --> ";
    }

    public void onFailed() {
        setTitle("启动失败");
        console(getTime() + "启动失败");
    };

    public void onReady() {
        loading = true;
        setTitle("运行中");
        stringBuffer.append("\n" + getTime() + "web服务已启动");
        startBtn.setText("停止");
        showIp.setVisible(true);
        showIp.setText("在浏览器中打开：http://" + getHostAddress() + "/preview.html");
        console(stringBuffer.toString());
    }
}